/*
 * Author: Ruben Unteregger
 * 
 */

package com.example.iorder.reservation.read;


import java.text.SimpleDateFormat;
import java.util.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.iorder.config.Config;
import com.example.iorder.reservation.Menuitem;
import com.example.iorder.reservation.Reservation;
import com.example.iorder.util.HTTPClient;
import com.example.iorder.util.MessageManager;
import com.example.iorder.util.NavigationManager;
import com.example.iorder.util.DataStorage;
import com.example.iorder.user.*;
import com.example.iorder.FullscreenActivity;
import com.example.iorder.R;
import com.example.iorder.SearchRestaurant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.AdapterView.OnItemLongClickListener;



/*
 *
 */
public class Activity_ShowAllReservations extends ListActivity implements OnScrollListener
{
	private ListReservationAdapter mCustomAdapter;
	private static ArrayList<Reservation> mReservationData = new ArrayList<Reservation>();
	private ProgressDialog mProgressDialog;
	private int mUserId = -1;
	
	
	
	public ArrayList<Reservation> getReservationData()
	{
		return(mReservationData);
	}
	
	
	/*
	 * 
	 * 
	 */
	public static Reservation getReservationById(int pID)
	{
		Reservation lRetVal = null;
		for (Reservation lTmp : mReservationData)
		{ 
			if (lTmp.getReservationId() == pID)
			{
				lRetVal = lTmp;
				break;
			}
		}
		
		return(lRetVal);
	}
	
	
	/*
	 * 
	 */
	private static int mCurrentReservation = -1;
	public static Reservation getSelectedReservation()
	{
		Reservation lRetVal = null;
		
		if (mCurrentReservation >= 0)
			lRetVal = getReservationById(mCurrentReservation);
		
		return(lRetVal);
	}	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// Initializing screen/object
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reservations_show_all);
		this.setTitle("iOrder | All reservations");

		// If user is not registered/logged in
		// force him to do so!!
		DataStorage lUserConfig = DataStorage.getInstance(getApplicationContext());
		String lUserID = lUserConfig.getStringElement("id");
		
		if (lUserID == null || lUserID.length() <= 0)
		{		
			String errorMessage = "U bent nog niet geregistreerd/ingelogd.";
			Drawable image = getResources().getDrawable(R.drawable.error_2);
			View layout = MessageManager.getMessageView(getLayoutInflater(), image, errorMessage);
			
			Toast messageView = new Toast(getApplicationContext());
			messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			messageView.setDuration(Toast.LENGTH_SHORT);
			messageView.setView(layout);
			messageView.show();
//			showDialog(null, "Foute gegevens!");			
		}
		else
		{
			try
			{
				mUserId = Integer.parseInt(lUserID);
				loadReservations(true);
			}
			catch (Exception lEx)
			{
				Toast.makeText(getApplicationContext(), "Error occurred: " + lEx.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
		
		try
		{
			// Add the header navigation
			RelativeLayout tabLayout = (RelativeLayout) findViewById(R.id.reservation_tab_layout);
			NavigationManager.addHeaderNavigation(this, tabLayout);
			NavigationManager.setCurrentTab(this, NavigationManager.TabButtons.MyReservations);
		}
		catch (Exception lEx)
		{
			Toast.makeText(getApplicationContext(), "Error occurred: " + lEx.getMessage(), Toast.LENGTH_LONG).show();
		}		
		
	}
	
	
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	protected void onResume() 
	{
		super.onResume();
		NavigationManager.setCurrentTab(this, NavigationManager.TabButtons.MyReservations);
	}

	
	
	/*
	 * 
	 * 
	 */
	private void loadReservations(boolean showHourglas)
	{
		mReservationData.clear();
		
		// Initializing hourglass while loading data.
		if (showHourglas)
		{
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setTitle(getResources().getString(R.string.loading_title));
			mProgressDialog.setMessage(getResources().getString(R.string.loading_message));
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();		
			
			setProgressBarIndeterminateVisibility(true);
		}
		
		
		new Thread() 
		{
			public void run() 
			{
				Message lMsg = new Message();
				HTTPClient lHTTPClient = null;
				String lSearchResult = "";
				String lPath = String.format("%s%d%s", Config.URL_USERS, mUserId, Config.URL_RESERVATIONS);

				try 
				{
					lHTTPClient = new HTTPClient(getBaseContext());
					lSearchResult = lHTTPClient.sendGETRequest(Config.IORDER_SERVER, lPath);

					lMsg.getData().putString("reservationdetails", lSearchResult);
					mSearchOutputHandler.sendMessage(lMsg);
				} catch (Exception lEx) {
					lMsg.getData().putString("exception", lEx.toString());
				}
			}
		}.start();		
	}
	
	
	/*
	 * Status delete handler
	 */
	private Handler mDeleteOutputHandler = new Handler()
	{
		public void handleMessage(Message msg) 
		{	
			String lNewData = msg.getData().getString("response");
			
			mProgressDialog.dismiss();			
			
			try 
			{
				JSONObject lJSONObj = new JSONObject(lNewData);

				if (lJSONObj.has("data") && lJSONObj.has("msg") && lJSONObj.has("status")) 
				{
					String lStatus = lJSONObj.get("status").toString();
					String lMessage = lJSONObj.get("msg").toString();
						
					if (lStatus.equals("200"))
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.message_reservation_deleted), Toast.LENGTH_LONG).show();
					else
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.error_occurred) + lMessage, Toast.LENGTH_LONG).show();
					
					loadReservations(false);
				}
				else
					Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
			} catch (JSONException lEx) {
				Toast.makeText(getBaseContext(), "JSONException exception: " + lEx.getMessage(), Toast.LENGTH_SHORT).show();
			} catch (Exception lEx) {
				Toast.makeText(getBaseContext(), "Regular exception: " + lEx.getMessage(), Toast.LENGTH_SHORT).show();
			}	
		}
	};
	

	
	/*
	 * Status cancel handler
	 */
	private Handler mCancelOutputHandler = new Handler()
	{
		public void handleMessage(Message msg) 
		{	
			String lNewData = msg.getData().getString("response");
			
			mProgressDialog.dismiss();			
			
			try 
			{
				JSONObject lJSONObj = new JSONObject(lNewData);

				if (lJSONObj.has("data") && lJSONObj.has("msg") && lJSONObj.has("status")) 
				{
					String lStatus = lJSONObj.get("status").toString();
					String lMessage = lJSONObj.get("msg").toString();
					
					if (lStatus.equals("200"))
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.message_cancellation_deleted), Toast.LENGTH_LONG).show();
					else
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.error_occurred) + lMessage, Toast.LENGTH_LONG).show();
														
					loadReservations(false);					
				}
				else
					Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
			} catch (JSONException lEx) {
				Toast.makeText(getBaseContext(), "JSONException exception: " + lEx.getMessage(), Toast.LENGTH_SHORT).show();
			} catch (Exception lEx) {
				Toast.makeText(getBaseContext(), "Regular exception: " + lEx.getMessage(), Toast.LENGTH_SHORT).show();
			}						
		}
	};	
	
	
	
	/*
	 * Status update handler
	 */
	private Handler mSearchOutputHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			String lNewData = msg.getData().getString("reservationdetails");
			
			mProgressDialog.dismiss();
			
			mReservationData.clear();
			TextView noReservationsView = (TextView) findViewById(R.id.noReservations);
			noReservationsView.setVisibility(View.VISIBLE);
			
			try 
			{
				JSONObject lJSONObj = new JSONObject(lNewData);

				if (lJSONObj.has("data") && lJSONObj.has("msg") && lJSONObj.has("status")) 
				{
					String lStatus = lJSONObj.get("status").toString();

					if (lStatus.equals("200"))
					{
						// Reservation details
						JSONArray lJSONDataArray = lJSONObj.getJSONArray("data");
						if (lJSONDataArray != null && lJSONDataArray.length() > 0)
						{
							noReservationsView.setVisibility(View.INVISIBLE);
							for (int i = 0; i < lJSONDataArray.length(); i++)
							{
								JSONObject lJSONDataObj = lJSONDataArray.getJSONObject(i);
								
								// Get reservation details
								JSONObject lJSONReservationDataObj = lJSONDataObj.getJSONObject("reservation");
								Integer lReservationStatus = lJSONReservationDataObj.getInt("Status");
								Integer lReservationId = lJSONReservationDataObj.getInt("ID");
								Integer lSystemUserID = lJSONReservationDataObj.getInt("SystemUserID");
								String lDate = lJSONReservationDataObj.getString("Date");
								
								// Time is behaving difficult. Needs workaround.
								String lTime = "";
								try
								{
									String lTimeTmp = lJSONReservationDataObj.getString("Time");							
									SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
									Date dtIn = inFormat.parse(lTimeTmp);  
									SimpleDateFormat outFormat = new SimpleDateFormat("HH:mm");
									lTime = outFormat.format(dtIn);									
								}
								catch (Exception lEx)
								{
									lTime = lJSONReservationDataObj.getString("Time");
								}


								// Get restaurant details
								JSONObject lJSONRestaurantDataObj = lJSONDataObj.getJSONObject("restaurant");
								Integer lRestaurantId = lJSONRestaurantDataObj.getInt("ID");
								String lName = lJSONRestaurantDataObj.getString("Name");
								String lAddress = lJSONRestaurantDataObj.getString("Address");
								String lCity = lJSONRestaurantDataObj.getString("City");
								String lPhoneNumber = lJSONRestaurantDataObj.getString("PhoneNumber");
								String lWebsite = lJSONRestaurantDataObj.getString("Website");
								String lCoordinates = lJSONRestaurantDataObj.getString("Coordinates");
								String lDescription = lJSONRestaurantDataObj.getString("Description");
								String lEmailAddress = lJSONRestaurantDataObj.getString("EmailAddress");

								// Get table details
								JSONObject lJSONTableDataObj = lJSONDataObj.getJSONObject("table");
								Integer lTableId = lJSONTableDataObj.getInt("ID");
								Integer lNoSeats = lJSONTableDataObj.getInt("Seats");
								String lTableType = lJSONTableDataObj.getString("Type");
								String lTabledetails = "Table no. " + lTableId + "\n("+ lNoSeats + " seats, type " +  lTableType + ")";
								
								
								// Get ordered menu items details
								ArrayList<Menuitem> lMenuitems = new ArrayList<Menuitem>();
								if (lJSONDataObj.has("menuitems"))
								{
									JSONArray lJSONArrayMenuItems = lJSONDataObj.getJSONArray("menuitems");
									if (lJSONArrayMenuItems.length() > 0)
									{
										for (int j = 0; j < lJSONArrayMenuItems.length(); j++)
										{
											try
											{
												JSONObject lJSONMenuItemDataObj = lJSONArrayMenuItems.getJSONObject(j);
												Integer lAmount = lJSONMenuItemDataObj.getInt("Amount");
												
												if (lJSONMenuItemDataObj.has("MenuItem"))
												{
													JSONObject lJSONMenuItem = lJSONMenuItemDataObj.getJSONObject("MenuItem");
													String lMenuName = lJSONMenuItem.getString("Title");
													String lMenuPriceStr = lJSONMenuItem.getString("Price");
													Float lMenuPrice = Float.parseFloat(lMenuPriceStr);
													
													lMenuitems.add(new Menuitem(lMenuName, lAmount, lMenuPrice));
												}
											}
											catch (Exception lEx)
											{}										
										}
										

									}
									
								}
								// Get user details
								JSONObject lJSONUserDataObj = lJSONDataObj.getJSONObject("user");
								
								mReservationData.add(new Reservation(lReservationId, lReservationStatus, lName, lAddress, lCity, lPhoneNumber, lDate, lTime, lTabledetails, lMenuitems));								
								
							}
						}
					}
					else
					{
						Toast.makeText(getBaseContext(), "Backend server error no : " + lJSONObj.get("status").toString(), Toast.LENGTH_SHORT).show();
					}				
				}
				else
				{
					Toast.makeText(getBaseContext(), getResources().getString(R.string.error_backend), Toast.LENGTH_SHORT).show();
				} // if (lJSO...
			} catch (JSONException lEx) {
				Toast.makeText(getBaseContext(), "JSONException exception: " + lEx.getMessage(), Toast.LENGTH_SHORT).show();
			} catch (Exception lEx) {
				Toast.makeText(getBaseContext(), "Regular exception: " + lEx.getMessage(), Toast.LENGTH_SHORT).show();
			}
			
			
			/*
			 * Reset/reassign the adapter
			 */
			ListView lReservationListView = getListView();
			mCustomAdapter = new ListReservationAdapter(Activity_ShowAllReservations.this, mReservationData);
	        setListAdapter(mCustomAdapter); 
	        lReservationListView.setOnScrollListener(Activity_ShowAllReservations.this);
	        lReservationListView.setOnItemLongClickListener(new OnItemLongClickListener() 
	            {
	        	  @Override
				  public boolean onItemLongClick(AdapterView<?> parent, View selectedView, int position, long id) 
	        	  {
					ResultsItemReservation selectedRestaurant = (ResultsItemReservation) selectedView.getTag();
					reserveAtSelectedReservation(selectedRestaurant);
					return true;
				  }
			});				
			
	        /*
	         * Postprocess the reservation list. 
	         */
//	        int lSize = lReservationListView.getCount();
//	        for (int i = 0; i < lSize; i++)
//	        {
//	        	LinearLayout lRowDetails = (LinearLayout) lCustomAdapter.getItem(i);
//	        }
//			RelativeLayout vwParentRowDetails = (RelativeLayout) lReservationListView.getChildAt(1);
//	        View v = getListView().getChildAt(0);
//	        if (v != null)
//	        {
//	            TextView someText = (TextView) v.findViewById(R.id.reservation_date_data);
//	            //Toast.makeText(getApplicationContext(), "DATA: " + someText.getText().toString(), Toast.LENGTH_SHORT).show();
//	            someText.setText("Hi! I updated you manually!");
//	        }
		}
	};

	
	
	/*
	 * 
	 * 
	 */
	class ListReservationAdapter extends BaseAdapter 
	{
		Context context;
		private ArrayList<Reservation> data;
		int count = 40;
		
		public ListReservationAdapter(Context context, ArrayList<Reservation> data) 
		{
			this.context = context;
			this.data = data;
		}
		
		@Override
		public int getCount() 
		{
			return data.size();
		}

		@Override
		public Object getItem(int position) 
		{
			return data.get(position);
		}

		@Override
		public long getItemId(int position) 
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			// Dummy results
			TextView view = new TextView(Activity_ShowAllReservations.this);
			view.setText("Entry: " + position);
			
			// Custom results with custom view (SearchResultsItem)
			View row = convertView;
			ResultsItemReservation itemHolder = new ResultsItemReservation();
			
			if (convertView == null) 
			{
				LayoutInflater inflater = ((Activity) context).getLayoutInflater();
				row = inflater.inflate(R.layout.reservations_show_item, parent, false);
				
				itemHolder.statusIcon = (ImageView) row.findViewById(R.id.reservation_status);
				itemHolder.deleteIcon = (ImageButton) row.findViewById(R.id.imageButtonDelete);
				itemHolder.reservationId = (TextView) row.findViewById(R.id.reservation_id);
				itemHolder.reservationTime = (TextView) row.findViewById(R.id.reservation_date);
				itemHolder.restName = (TextView) row.findViewById(R.id.reservation_rest_name);
				itemHolder.restCity = (TextView) row.findViewById(R.id.reservation_rest_city);		
				
				row.setTag(itemHolder);
			} else {
				itemHolder = (ResultsItemReservation) row.getTag();
			}
			
			Reservation reservation = null;
			if (position < data.size())
				reservation = data.get(position);
			
			/*
			 * Assign the GUI elements their value
			 */			
			if (itemHolder != null && reservation != null) 
			{
				Date lToday = Calendar.getInstance().getTime();
				Date lActualReservationDate = getDateByString(reservation.getDate(), "yyyy-MM-dd");
			
				
				/*
				 * Determine and assign Delete/Cancel icon
				 */
				if (lActualReservationDate.getYear() == lToday.getYear() && 
					lActualReservationDate.getMonth() == lToday.getMonth() &&
					lActualReservationDate.getDay() == lToday.getDay())
				{
					itemHolder.deleteIcon.setImageResource(R.drawable.delete_icon);
					itemHolder.deleteIcon.setEnabled(false);
					itemHolder.restName.setTextColor(getResources().getColor(R.color.reservationActive));
					itemHolder.restCity.setTextColor(getResources().getColor(R.color.reservationActive));
					itemHolder.reservationTime.setTextColor(getResources().getColor(R.color.reservationInactive));
				}
				else if (lActualReservationDate.before(lToday))
				{	
					itemHolder.deleteIcon.setImageResource(R.drawable.delete_icon);
					itemHolder.deleteIcon.setEnabled(true);
					itemHolder.restName.setTextColor(getResources().getColor(R.color.reservationInactive));
					itemHolder.restCity.setTextColor(getResources().getColor(R.color.reservationInactive));
					itemHolder.reservationTime.setTextColor(getResources().getColor(R.color.reservationInactive));
				}				
				else
				{
					itemHolder.deleteIcon.setImageResource(R.drawable.minus_icon);
					itemHolder.deleteIcon.setEnabled(true);
					itemHolder.restName.setTextColor(getResources().getColor(R.color.reservationActive));
					itemHolder.restCity.setTextColor(getResources().getColor(R.color.reservationActive));
					itemHolder.reservationTime.setTextColor(getResources().getColor(R.color.reservationActive));
				}
				

				/*
				 * Determine and assign reservation status icon
				 */
				int lStatus = reservation.getStatus();
				if (lStatus == 0)
					itemHolder.statusIcon.setImageResource(R.drawable.questionmark_icon);
				else if (lStatus == 1)
					itemHolder.statusIcon.setImageResource(R.drawable.checkmark_icon);
				else if (lStatus == 2)
					itemHolder.statusIcon.setImageResource(R.drawable.cross_icon);
				
				/*
				 * Assign the value
				 */
				itemHolder.reservationId.setText(Integer.toString(reservation.getReservationId()));				
				itemHolder.restName.setText(reservation.getName()); 
				itemHolder.restCity.setText(reservation.getCity()); 				
				itemHolder.reservationTime.setText(reservation.getDate() + " " + reservation.getTime());
			}
			
			return row;
		}
		
		public ArrayList<Reservation> getRestaurants() { return data; }
	}	
	
	
	/*
	 * 
	 * 
	 */
	public void deleteButtonClick(View view) 
	{

		/*
		 * Get reservation content
		 */
		LinearLayout l = (LinearLayout) view.getParent();
		RelativeLayout r = (RelativeLayout) l.findViewById(R.id.reservation_content);
		
        final String lReservationId = ((TextView) r.findViewById(R.id.reservation_id)).getText().toString();
        String lReservationDate = ((TextView) r.findViewById(R.id.reservation_date)).getText().toString();
        		
		
		Date lToday = Calendar.getInstance().getTime();
		Date lActualReservationDate = getDateByString(lReservationDate, "yyyy-MM-dd");

		
		/*
		 * Check if Cancel or Delete request.
		 */	

		// Cancellation is today	
		if (lActualReservationDate.getYear() == lToday.getYear() && 
				lActualReservationDate.getMonth() == lToday.getMonth() &&
				lActualReservationDate.getDay() == lToday.getDay())
		{
		// Delete request
		} else if (lActualReservationDate.before(lToday)) {
			deleteReservation(lReservationId);
		// Cancellation request				
		} else {		
			cancelReservation(lReservationId);
		}	
	}
	
	
	/*
	 * 
	 * 
	 */
	public void showButtonClick(View view) 
	{		
	    //get the row the clicked button is in
		LinearLayout vwParentRow = (LinearLayout) view.getParent();
		RelativeLayout vwParentRowDetails = (RelativeLayout) vwParentRow.getChildAt(1);
		
		TextView lReservationIdObj = (TextView) vwParentRowDetails.getChildAt(3);
		mCurrentReservation = Integer.parseInt(lReservationIdObj.getText().toString());

		// 2. start the activity		
		Intent lReservationIntent = new Intent(this, ActivityTabhost_ShowReservation.class);	
		startActivity(lReservationIntent);	
	}
		
	
	
	/*
	 * 
	 * 
	 */
	private static class ResultsItemReservation 
	{
		public ImageView statusIcon;
		public ImageButton deleteIcon;
		public TextView reservationId;
		public TextView reservationTime;
		public TextView restName;
		public TextView restCity;
	}

	

	
	/*
	 * 
	 * 
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) 
	{
		boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;
		
		if (loadMore && visibleItemCount != totalItemCount) 
		{
			mCustomAdapter.count += visibleItemCount;
			mCustomAdapter.notifyDataSetChanged();
		} // if (loadMor...
	}

	
	/*
	 * 
	 * 
	 */
	private void reserveAtSelectedReservation(ResultsItemReservation selectedReservation) 
	{
//		AlertDialog.Builder builder = new AlertDialog.Builder(this);
//		String restaurantName = selectedReservation.restName.getText().toString();
//		builder.setMessage("Start reservation at " + restaurantName).setTitle(R.string.alert_dialog_title);
//		builder.setPositiveButton(R.string.lable_button_ok,
//				new DialogInterface.OnClickListener() 
//				{
//					public void onClick(DialogInterface dialog, int id) 
//					{
//						// User clicked OK button
//					}
//				});
//		AlertDialog newDialog = builder.create();
//		newDialog.show();
	}	
	

	/*
	 * 
	 * 
	 */
	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) 
	{
		// TODO Auto-generated method stub		
	}	
	
	
	/*
	 * 
	 * 
	 */
	private Date getDateByString(String pDateString, String pDateFormat)
	{
		SimpleDateFormat lDateFormatter = new SimpleDateFormat(pDateFormat);
		Date lActualReservationDate = null;
//		
		try 
		{
			lActualReservationDate = lDateFormatter.parse(pDateString); //lReservationDateString);
		} 
		catch (java.text.ParseException e)
		{
			e.printStackTrace();
		}	

		return(lActualReservationDate);		
	}
	
	
	
	/*
	 * 
	 * 
	 */
	public void cancelReservation(final String pReservationId)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.title_reservation_cancel));
		builder.setMessage(getResources().getString(R.string.title_reservation_cancel_confirmation));
		builder.setCancelable(true);
		builder.setPositiveButton(getResources().getString(R.string.label_ok), new DialogInterface.OnClickListener() 
						{
							  public void onClick(DialogInterface arg0, int arg1) 
							  {
								  Runnable r = new CancelThread(pReservationId);
								  new Thread(r).start();								  							  
							  }
						});
		
		builder.setNegativeButton(getResources().getString(R.string.label_cancel), new DialogInterface.OnClickListener() 
						{			       
			  				public void onClick(DialogInterface arg0, int arg1) 
			  				{
			  					// do something when the Cancel button is clicked
			  				}
			  			});	
		
		builder.create().show();			
	}	
	
	
	/*
	 * 
	 * 
	 */
	public void deleteReservation(final String pReservationId)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle(getResources().getString(R.string.title_reservation_delete));
		builder.setMessage(getResources().getString(R.string.title_reservation_delete_confirmation));
		
		
		builder.setCancelable(true);
		builder.setPositiveButton(getResources().getString(R.string.label_ok), new DialogInterface.OnClickListener() 
						{
							  public void onClick(DialogInterface arg0, int arg1) 
							  {
								  Runnable r = new DeleteThread(pReservationId);
								  new Thread(r).start();								  							  
							  }
						});
		
		builder.setNegativeButton(getResources().getString(R.string.label_cancel), new DialogInterface.OnClickListener() 
						{			       
			  				public void onClick(DialogInterface arg0, int arg1) 
			  				{
			  					// do something when the Cancel button is clicked
			  				}
			  			});	
		
		builder.create().show();			
	}	
	
	
	
	
	
	/*
	 * 
	 * 
	 */
	public class DeleteThread implements Runnable 
	{
		private String mReservationId;
		
		public DeleteThread(Object pReservationId) 
		{
			mReservationId = pReservationId.toString();
		}

		
		public void run() 
		{
       		Message lMsg = new Message();
       		String lPath = "";
       		HTTPClient lHttpClient = null;
       		String lDeleteResult = "";
       		String lUpdateString = "{\"Status\": " + Config.RESERVATION_STATUS2INT.get("RESERVATION_DELETED") + "}";
       		
       		
       		try 
       		{
       			lPath = Config.URL_RESERVATIONS + mReservationId;
       			lHttpClient = new HTTPClient(getBaseContext());
      			lDeleteResult = lHttpClient.sendPUTRequest(Config.IORDER_SERVER, lPath, lUpdateString);
       			
       			lMsg.getData().putString("response",  lDeleteResult);
       			mDeleteOutputHandler.sendMessage(lMsg);
       		} 
       		catch (Exception e) 
       		{
       			lMsg.getData().putString("exception", e.toString());
       		}			   
		}
			
	}	

	
	/*
	 * 
	 * 
	 */
	public class CancelThread implements Runnable 
	{
		private String mReservationId;
		
		public CancelThread(Object pReservationId) 
		{
			mReservationId = pReservationId.toString();
		}

		public void run() 
		{
       		Message lMsg = new Message();
       		String lPath = "";
       		HTTPClient lHttpClient = null;
       		String lDeleteResult = "";
       		String lUpdateString = "{\"Status\": " + Config.RESERVATION_STATUS2INT.get("CANCELLATION_REQUESTED") + "}";
       		
       		try 
       		{
       			lPath = Config.URL_RESERVATIONS + mReservationId;
       			lHttpClient = new HTTPClient(getBaseContext());
      			lDeleteResult = lHttpClient.sendPUTRequest(Config.IORDER_SERVER, lPath, lUpdateString);

      			lMsg.getData().putString("response",  lDeleteResult);
       			mDeleteOutputHandler.sendMessage(lMsg);
       		} 
       		catch (Exception e) 
       		{
       			lMsg.getData().putString("exception", e.toString());
       		}			   
		}
			
	}		
	
}
